package com.txsj.scan.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.greendao.EpcInfoDao;
import com.greendao.GoodsInfoDao;
import com.txsj.scan.R;
import com.txsj.scan.adapter.InventoryBatchAdapter;
import com.txsj.scan.base.BaseActivity;
import com.txsj.scan.bean.EpcInfo;
import com.txsj.scan.bean.GoodsInfo;
import com.txsj.scan.bean.InventoryBatchBean;
import com.txsj.scan.bean.WarehouseBean;
import com.txsj.scan.db.GreenDaoUtils;
import com.txsj.scan.presenter.InventoryBatchPresenter;
import com.txsj.scan.refresh.XRefreshView;
import com.txsj.scan.utils.SoftInputUtils;
import com.txsj.scan.utils.glide.GlideImgManager;
import com.txsj.scan.view.InventoryBatchIView;
import com.txsj.scan.widget.DragFloatActionButton;
import com.txsj.scan.widget.TitleBarView;
import com.txsj.scan.widget.dialog.InputNumberDialog;
import com.txsj.scan.widget.swipemenu.SwipeRecyView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangchuangjun on 2018/11/21
 * Desc: 盘点批次页面
 */

public class InventoryBatchActivity extends BaseActivity<InventoryBatchPresenter> implements InventoryBatchIView {

    public static final int REQUEST_ADD_BATC_CODE = 0x114;
    public static final int RESULT_COMMIT_BATC_CODE = 0x115;
    public static final int RESULT_REFRESH_CODE = 0x116;
    public static final int RESULT_SCAN_BATC_CODE = 0x117;

    TitleBarView mTitle;
    ImageView iv_goods_pic;
    TextView tv_goods_name, tv_goods_stockCount;
    TextView tv_goods_num;
    SwipeRecyView recyclerView;
    InventoryBatchAdapter adapter;

    private List<InventoryBatchBean> commitList;//变动后需要提交的列表

    DragFloatActionButton fab;
    XRefreshView xRefreshView;
    String from;//来源
    String type = "-1";// 1: 当前仓库  2：其他商品  0:新增盘点  4:扫码返回
    String expired_date = "9999-12-31";
    GoodsInfo goods;
    GoodsInfo epcGoodsInfo;
    GoodsInfo goodsInfo;
    int pageNo;
    String warehouseId;
    WarehouseBean warehouseBean;//当前仓库
    long gs1_num;
    List<EpcInfo> epcInfoList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inventory_batch);
        initView();
        initData();
    }

    private void initData() {

        if (null == getIntent() || null == getIntent().getStringExtra("data") || null == getIntent().getStringExtra("from")) return;
        from = getIntent().getStringExtra("from");
        String warehouseJson = getIntent().getStringExtra("warehouse");
        warehouseBean = new Gson().fromJson(warehouseJson,WarehouseBean.class);
        warehouseId = warehouseBean.getWarehouse_id()+"";
        if (from.equals(InventoryActivity.class.getSimpleName())) {
            type = getIntent().getStringExtra("type");
            if (type.equals("0")) {//从盘点列表点击过来
                String jsonObj = getIntent().getStringExtra("data");
                epcGoodsInfo = new Gson().fromJson(jsonObj, GoodsInfo.class);
                GlideImgManager.getLoadRoundImg(this, epcGoodsInfo.getGoods_img(), iv_goods_pic);

                //根据缓存中的goods_id获取warehouseid
//                List<GoodsInfo> goodsInfoList = GreenDaoUtils.getSingleTon().getmDaoSession().getGoodsInfoDao().queryBuilder()
//                        .where(GoodsInfoDao.Properties.Goods_id.eq(epcGoodsInfo.getGoods_id()))
//                        .list();
                goodsInfo = epcGoodsInfo;
//                if (null != goodsInfoList && goodsInfoList.size() > 0) {
                    gs1_num = epcGoodsInfo.getGs1_num();
//                }

                //通过传过来的strEPC来判断是哪个批次信息
                epcInfoList = new ArrayList<>();
                List<EpcInfo> epcList = epcGoodsInfo.getEpcList();
                if (null != epcList && epcList.size() > 0) {
                    for (EpcInfo strEpc : epcList) {
                        String epcCode = strEpc.getStrEpc().substring(9, strEpc.getStrEpc().length());
                        long id = Long.parseLong(epcCode, 16);
                        List<EpcInfo> list = GreenDaoUtils.getSingleTon().getmDaoSession().getEpcInfoDao().queryBuilder()
                                .where(EpcInfoDao.Properties.Tag_id.eq(id))
                                .list();
                        if (null != list && list.size() > 0) {
                            epcInfoList.add(list.get(0));
                        }
                    }
                }

                tv_goods_name.setText(epcGoodsInfo.getGoods_name());
                tv_goods_num.setText(epcGoodsInfo.getGoods_num());
                tv_goods_stockCount.setText("库存：" + goodsInfo.getInventory_keep());

            }else {  //从盘点列表扫码过来
                String json = getIntent().getStringExtra("data");
                goods = new Gson().fromJson(json,GoodsInfo.class);
                GlideImgManager.getLoadRoundImg(this, goods.getGoods_img(), iv_goods_pic);
                tv_goods_name.setText(goods.getGoods_name());
                tv_goods_num.setText(goods.getGoods_num());
                tv_goods_stockCount.setText("库存："+goods.getInventory_keep());

                //根据缓存中的goods_id获取warehouseid
                List<GoodsInfo> goodsInfoList = GreenDaoUtils.getSingleTon().getmDaoSession().getGoodsInfoDao().queryBuilder()
                        .where(GoodsInfoDao.Properties.Goods_id.eq(goods.getGoods_id()),
                                GoodsInfoDao.Properties.Warehouse_id.eq(warehouseId))
                        .list();
                goodsInfo = goodsInfoList.get(0);
                if (null != goodsInfoList && goodsInfoList.size() >0){
                    gs1_num = goodsInfoList.get(0).getGs1_num();
                }

            }
        }else if (from.equals(GoodsListActivity.class.getSimpleName())){//从商品列表点击过来
            type = getIntent().getStringExtra("type");
            String json = getIntent().getStringExtra("data");
            goods = new Gson().fromJson(json,GoodsInfo.class);
            GlideImgManager.getLoadRoundImg(this, goods.getGoods_img(), iv_goods_pic);
            tv_goods_name.setText(goods.getGoods_name());
            tv_goods_num.setText(goods.getGoods_num());
            tv_goods_stockCount.setText("库存："+goods.getInventory_keep());

            //根据缓存中的goods_id获取warehouseid
            List<GoodsInfo> goodsInfoList = GreenDaoUtils.getSingleTon().getmDaoSession().getGoodsInfoDao().queryBuilder()
                    .where(GoodsInfoDao.Properties.Goods_id.eq(goods.getGoods_id()),
                            GoodsInfoDao.Properties.Warehouse_id.eq(warehouseId))
                    .list();
            goodsInfo = goodsInfoList.get(0);
            if (null != goodsInfoList && goodsInfoList.size() >0){
                gs1_num = goodsInfoList.get(0).getGs1_num();
            }
        }

        commitList = new ArrayList<>();

        //只有当前仓库才能进行批次盘点，其他商品只能新增批次
        if (type.equals("1") || type.equals("0") ||type.equals("4") ) {
            presenter.getBatchHttpData(gs1_num, pageNo, warehouseId);
        }
    }

    private void initView() {
        mTitle = (TitleBarView) findViewById(R.id.mTitle);
        iv_goods_pic = (ImageView) findViewById(R.id.iv_goods_pic);
        tv_goods_name = (TextView) findViewById(R.id.tv_goods_name);
        tv_goods_num = (TextView) findViewById(R.id.tv_goods_num);
        tv_goods_stockCount = (TextView) findViewById(R.id.tv_goods_stockCount);
        fab = (DragFloatActionButton) findViewById(R.id.fab);

        xRefreshView = (XRefreshView) findViewById(R.id.xRefreshView);
        recyclerView = (SwipeRecyView) findViewById(R.id.recyclerView);
        RecyclerView.LayoutManager manager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        adapter = new InventoryBatchAdapter(this);
        recyclerView.setAdapter(adapter);
        initEmptyView();
        xRefreshView.enableEmptyView(false);
        xRefreshView.setPullRefreshEnable(false);
        xRefreshView.setAutoLoadMore(true);
        xRefreshView.startRefresh();
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener(){
            @Override
            public void onRefresh(boolean isPullDown) {
                super.onRefresh(isPullDown);
                commitList.clear();
                adapter.clear();
                pageNo = 1;
                //只有当前仓库才能进行批次盘点，其他商品只能新增批次
                if (type.equals("1") || type.equals("0") ||type.equals("4") ) {
                    presenter.getBatchHttpData(gs1_num, pageNo, warehouseId);
                }else {
                    xRefreshView.stopRefresh();
                }
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                pageNo++;
                //只有当前仓库才能进行批次盘点，其他商品只能新增批次
                if (type.equals("1") || type.equals("0") ||type.equals("4") ) {
                    presenter.getBatchHttpData(gs1_num, pageNo, warehouseId);
                }else {
                    xRefreshView.stopLoadMore();
                }
            }
        });

        adapter.setChangeListener(new InventoryBatchAdapter.OnEditTextChangeListener() {
            @Override
            public void onClick(final int position) {
                InputNumberDialog dialog = new InputNumberDialog(InventoryBatchActivity.this);
                dialog.initData(adapter.getList().get(position).getChange_num());
                dialog.setListener(new InputNumberDialog.OnOkChangeListener() {
                    @Override
                    public void onChange(long count) {
                        // 先隐藏键盘
                        SoftInputUtils.hideSoftInput(InventoryBatchActivity.this);
                        adapter.updateData(position,count);
                        changeInventoryList(adapter.getList().get(position));
                    }
                });
                dialog.show();
            }

            @Override
            public void onDecrease(int position) {
                long count = adapter.getList().get(position).getChange_num();
                if (count > 0) {
                    adapter.updateData(position,--count);
                    changeInventoryList(adapter.getList().get(position));
                }
            }

            @Override
            public void onIncrease(int position) {
                long count = adapter.getList().get(position).getChange_num();
                adapter.updateData(position,++count);
                changeInventoryList(adapter.getList().get(position));

            }

            @Override
            public void onDelete(int position) {
                InventoryBatchBean bean = adapter.getList().get(position);
                adapter.deleteItem(position);
                deleteCommitData(bean);
            }
        });

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(InventoryBatchActivity.this, AddBatchActivity.class);
                intent.putExtra("data",new Gson().toJson(goodsInfo));
                intent.putExtra("warehouse",new Gson().toJson(warehouseBean));
                startActivityForResult(intent, REQUEST_ADD_BATC_CODE);
            }
        });

        //处理悬浮按钮的点击
        fab.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_MOVE:

                        break;
                    case MotionEvent.ACTION_UP:

                        break;
                }
                return false;
            }
        });

    }

    /**
     * 删除不想盘点的批次
     * @param bean
     */
    private void deleteCommitData(InventoryBatchBean bean) {
        if (commitList.size() == 0) {
            return;
        }
        int position = 0;
        boolean isContains = false;
        for (int i = 0;i<commitList.size();i++){
            if (bean.getExpiry_time().equals(commitList.get(i).getExpiry_time())){
                isContains = true;
                position=i;
                break;
            }
        }
        if (isContains){
            commitList.remove(position);
        }
    }

    /**
     * 对批次数量进行改变
     * @param bean
     */
    private void changeInventoryList(InventoryBatchBean bean) {
        if (commitList.size() == 0) {
            InventoryBatchBean changeBean = bean;
            changeBean.setGoods_count(bean.getChange_num() - bean.getInventory_keep());
            commitList.add(changeBean);
            return;
        }
        boolean isContains = false;
        for (int i = 0; i < commitList.size(); i++) {
            if (commitList.get(i).getExpiry_time().equals(bean.getExpiry_time())) {
                isContains = true;
                commitList.get(i).setGoods_count(bean.getChange_num() - bean.getInventory_keep());
                break;
            }
        }
        if (!isContains) {
            InventoryBatchBean changeBean = bean;
            changeBean.setGoods_count(bean.getChange_num() - bean.getInventory_keep());
            commitList.add(changeBean);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (null != data && null != data.getSerializableExtra("data")){
            if (requestCode == REQUEST_ADD_BATC_CODE){
                InventoryBatchBean inventoryBatchBean = (InventoryBatchBean) data.getSerializableExtra("data");
                /**
                 * 回调完成后，对当前fragment展示的type进行判断
                 * type==0 :说明是新增盘点，对扫描过来的数据进行盘点
                 * type==1 :说明是当前仓库，进行新增批次展示或者覆盖
                 * type==2 :说明是其他商品，只对当前仓库新增批次，不展示finish,回到商品列表页
                 */
                if (type.equals("1") || type.equals("0") ||type.equals("4") ) {
                    //如果是由当前仓库下的返回的数据进行批次添加
                    judgeData(inventoryBatchBean);
                }else {
                    //由其他商品缓存回来的数据刷新一下本地仓库下的缓存
                    presenter.getGoodsListAndCache(warehouseBean);
                }
            }
        }
    }

    /**
     * 添加完成后的数据返回结果对当前展示的集合进行合并或添加
     * @param batchBean
     */
    private void judgeData(InventoryBatchBean batchBean) {
        adapter.setNewBatch(batchBean);
    }

    /**
     * 确认提交
     * @param view
     */
    public void clickConfirm(View view) {
        if (type.equals("0")){
            for (InventoryBatchBean batchBean:adapter.getList()){
                changeInventoryList(batchBean);
            }
        }
        if (commitList.size() >0){
            Intent intent = getIntent();
            intent.putExtra("data",new Gson().toJson(commitList));
            intent.putExtra("type",type);
            intent.putExtra("goods_info",new Gson().toJson(goodsInfo));
            if (type.equals("0")) {
                setResult(RESULT_COMMIT_BATC_CODE, intent);
            }else {
                setResult(RESULT_SCAN_BATC_CODE, intent);
            }
            finish();
        }
    }

    @Override
    protected InventoryBatchPresenter providePresenter() {
        return presenter = new InventoryBatchPresenter(this);
    }

    @Override
    public Context context() {
        return this;
    }

    @Override
    public void onSuccess(List<InventoryBatchBean> list) {
        hideLoading();
        xRefreshView.stopLoadMore();
        if (null == list || list.size() == 0){
            if (pageNo == 1){
                onError("暂无数据");
            }else {
                onLoadMoreError("加载失败");
            }
        }else {
            if (pageNo == 1){
                xRefreshView.stopRefresh();
            }else {
                xRefreshView.stopLoadMore();
            }


            //当来源是盘点，将扫描到的信息赋值到该数据上
            if (type.equals("0")){
                for (int i = 0;i<list.size();i++) {
                    long count = 0;
                    for (int j = 0; j < epcInfoList.size(); j++) {
                        if (list.get(i).getBatch_id() == epcInfoList.get(j).getBatch_id()){
                            count++;
                        }
                    }
                    if (count > 0){
                        list.get(i).setChange_num(count);
                    }
                }
            }
            adapter.setList(list, pageNo);


        }
    }

    @Override
    public void onCacheSuccess() {
        setResult(RESULT_REFRESH_CODE);//把其他商品添加到当前仓库之后提示选择商品界面刷新数据
        finish();
    }

    @Override
    public void onLoading() {
        if (pageNo == 1){
            showLoading();
        }
    }

    @Override
    public void onError(String msg) {
        hideLoading();
        showErrorMsg(msg);
        xRefreshView.enableEmptyView(true);
        xRefreshView.stopRefresh();
    }

    @Override
    public void onLoadEnd(String msg) {
        xRefreshView.stopLoadMore();
        hideLoading();
    }

    @Override
    public void onLoadMoreError(String msg) {
        xRefreshView.stopLoadMore();
        hideLoading();
    }

    Button btn_empty_reload;

    /**
     * 列表数据为空时 显示的View
     */
    private void initEmptyView() {
        View emptyView = View.inflate(this, R.layout.view_empty, null);
        btn_empty_reload = (Button) emptyView.findViewById(R.id.btn_empty_reload);
        xRefreshView.setEmptyView(emptyView);
        btn_empty_reload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                xRefreshView.startRefresh();
            }
        });
    }
}
